/**
  HomeMade by shoe[box]
 
  Redistribution and use in source and binary forms, with or without 
  modification, are permitted provided that the following conditions are
  met:

  * Redistributions of source code must retain the above copyright notice, 
    this list of conditions and the following disclaimer.
  
  * Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the 
    documentation and/or other materials provided with the distribution.
  
  * Neither the name of shoe[box] nor the names of its 
    contributors may be used to endorse or promote products derived from 
    this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 
  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

package org.shoebox.guacamole.view {

	import org.shoebox.apps.frakconsole.core.Frak;
	import org.shoebox.display.BoxColor;
	import org.shoebox.display.RGBCol;
	import org.shoebox.guacamole.Cameras.BasicCam;
	import org.shoebox.guacamole.assets.AssetManager;
	import org.shoebox.guacamole.core.Light;
	import org.shoebox.guacamole.core.RenderTask;
	import org.shoebox.guacamole.core.SimpleLight;
	import org.shoebox.guacamole.interfaces.IContainer;
	import org.shoebox.guacamole.view.abstracts.GuaProjectable;
	import org.shoebox.guacamole.view.containers.GuaContainer;
	import org.shoebox.utils.logger.Logger;
	import flash.display.Stage;
	import flash.display.Stage3D;
	import flash.display3D.Context3D;
	import flash.display3D.Context3DBlendFactor;
	import flash.display3D.Context3DCompareMode;
	import flash.display3D.Context3DProgramType;
	import flash.display3D.Context3DRenderMode;
	import flash.display3D.Context3DTriangleFace;
	import flash.display3D.Program3D;
	import flash.display3D.textures.TextureBase;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.geom.Matrix3D;
	import flash.geom.Rectangle;
	import flash.system.Capabilities;
	
	/**
	* org.shoebox.guacamole.view.Scene2D
	* @author shoebox
	*/
	public class GuaScene extends EventDispatcher implements IContainer{
		
		public var activeCam			: BasicCam;
		public var refContext3D		: Context3D;
		public var iFps				: int;
		public var width				: int;
		public var height			: int;
		public var rBounds			: Rectangle;
		public var refStage			: Stage;
		public var sRenderMode			: String;
		public var root				: GuaContainer;
		public var iStageId			: uint;
		
		protected var _bBackBufferOn		: Boolean = false;
		protected var _iHalfW			: int;
		protected var _iHalfH			: int;
		protected var _oStage3D		: Stage3D;
		protected var _progDepth		: Program3D;
		protected var _vTexturesBuffer	: Vector.<TextureBase>;
		protected var _oTask			: RenderTask;
		
		// -------o constructor
			
			/**
			* Scene3D constructor
			* @public
			* @param 
			* @return
			*/
			public function GuaScene( refStage : Stage = null , sRenderMode : String = Context3DRenderMode.AUTO , iStageId : uint = 0 , rBounds : Rectangle = null) : void {
				
				super( );
				
				if( !refStage )
					throw new ArgumentError( );
				
				_vTexturesBuffer = new Vector.<TextureBase>( 8 , true );
				AssetManager.setStageRef( this );
				
				this.sRenderMode = sRenderMode;
				this.refStage = refStage;
				this.iStageId = iStageId;
				this.rBounds = rBounds;
				
				if( !rBounds )
					rBounds = new Rectangle( 0 , 0 , refStage.stageWidth , refStage.stageHeight );
				
				_iHalfW = refStage.stageWidth / 2;
				_iHalfH = refStage.stageHeight / 2;
				
				_init( );
			}

		// -------o public
			
			/**
			* setSize function
			* @public
			* @param 
			* @return
			*/
			final public function setSize( w : int , h : int ) : void {
				
				rBounds = new Rectangle( 0 , 0 , w , h );
				
				this.width  = w;
				this.height = h;
				
				_iHalfW = w / 2;
				_iHalfH = h / 2;
				
				if( refContext3D ){
					_bBackBufferOn = true;
					refContext3D.configureBackBuffer( rBounds.width , rBounds.height , 0 , true );
				}
				refContext3D.setScissorRectangle( rBounds );
				//refContext3D.viewPort = rBounds = new Rectangle( 0 , 0 , w , h );
				
			}
			
			/**
			* render function
			* @public
			* @param 
			* @return
			*/
			public function render( ref : Context3D , oMat : Matrix3D ) : void {
			
			}
			
			/**
			* redraw function
			* @public
			* @param 
			* @return
			*/
			final public function update( ) : void {
				
				if( !refContext3D || !_bBackBufferOn ) //TODO : Exception or not ?
					return;
				
				//var nT : Number = getTimer( );
				
				if( !_oTask )
					_oTask = new RenderTask( this , activeCam.getViewProjection( ) );
				
				refContext3D.clear( 0.7 , 0.7 , 0.7 , 1 );
				root.render( _oTask );
				refContext3D.present( );
				//trace('Render time ::: '+( getTimer() - nT ) );
			}
			
			/**
			* setAmbient function
			* @public
			* @param 
			* @return
			*/
			final public function setAmbient( u : uint ) : void {
				var col : RGBCol = BoxColor.HEXtoRGBOBJ( u );
				refContext3D.setProgramConstantsFromVector ( Context3DProgramType.FRAGMENT, 2 , Vector.<Number>( [ col.red / 255 , col.green / 255 , col.blue / 255 , 1 ] ) );		// Ambient Color
			}
			
			/**
			* setAmbientVector function
			* @public
			* @param 
			* @return
			*/
			final public function setAmbientVector( v : Vector.<Number> ) : void {
				refContext3D.setProgramConstantsFromVector ( Context3DProgramType.FRAGMENT, 2 , v );		// Ambient Color
			}
			
			/**
			* function addChild( c : AProjectable , b : Boolean = false ) : void function
			* @public
			* @param 
			* @return
			*/
			final public function addChild( c : GuaProjectable , b : Boolean = false ) : Boolean{
				return root.addChild( c , b );
			}
			
			/**
			* addChilds function
			* @public
			* @param 
			* @return
			*/
			final public function addChilds( v : Vector.<GuaProjectable> ) : void {
				root.addChilds( v );
			}
			
			/**
			* removeAllChilds function
			* @public
			* @param 
			* @return
			*/
			final public function removeAllChilds() : void {
				root.removeAllChilds( );
			}
			
			/**
			* getChilds function
			* @public
			* @param 
			* @return
			*/
			final public function getChilds( ) : Vector.<GuaProjectable> {
				return root.getChilds( new Vector.<GuaProjectable>() );
			}
			
			/**
			* setTextureAt function
			* @public
			* @param 
			* @return
			*/
			final public function setTextureAt( sampler : int , texture : TextureBase ) : void {
				
				if( _vTexturesBuffer[ sampler ] !== texture ){
					refContext3D.setTextureAt ( sampler , texture );
					_vTexturesBuffer[ sampler ] = texture;
				}
			}
			
		// -------o protected
			
			/**
			* 
			*
			* @param 
			* @return
			*/
			final protected function _init() : void {
				trc('init');
				_oStage3D = refStage.stage3Ds[ iStageId ];
				_oStage3D.addEventListener( Event.CONTEXT3D_CREATE , _onContext , false , 10 , true );
				_oStage3D.requestContext3D( sRenderMode );
			}
			
			/**
			* 
			*
			* @param 
			* @return
			*/
			final protected function _onContext( e : Event ) : void {
				_oStage3D.removeEventListener( Event.CONTEXT3D_CREATE , _onContext , false );
				//
					refContext3D = refStage.stage3Ds[ iStageId ].context3D;
					refContext3D.enableErrorChecking = Capabilities.isDebugger;
					refContext3D.setCulling( Context3DTriangleFace.NONE );
					refContext3D.setBlendFactors( Context3DBlendFactor.ONE, Context3DBlendFactor.ONE_MINUS_SOURCE_ALPHA ); //ONE_MINUS_SOURCE_ALPHA //TODO : Blendmodes
					refContext3D.setDepthTest(false, Context3DCompareMode.ALWAYS);
					Frak.watch(refContext3D.driverInfo);
				
				
				//
					setAmbient( 0xFFFFFF );
					if( !rBounds )
						setSize( refStage.stageWidth , refStage.stageHeight );
					
				//
					root = new GuaContainer( );
					root.scene = this;
					dispatchEvent( new Event( Event.INIT ));
				
			}
			
			/**
			* 
			*
			* @param 
			* @return
			*/
			final protected function _makeOrthoMat(left : Number, right : Number, top : Number, bottom : Number, zNear : Number = -1, zFar : Number = 1) : Matrix3D {

		            return new Matrix3D(Vector.<Number>([
		                                                    2 / (right - left), 0, 0, 0,
		                                                    0, 2 / (top - bottom), 0, 0,
		                                                    0, 0, 1 / (zFar - zNear), 0,
		                                                    0, 0, 0, 1
		                                                ]));
        		}
			
		// -------o misc

			public static function trc( ...args : Array ) : void {
				Logger.log(GuaScene, args);
			}
	}
}
